var mapTool = {
    api: 'https://webapi.amap.com/maps?v=1.4.13&key=8c1ed5f1f8d15fccbffcf493cc9cea93&plugin=AMap.LineSearch,AMap.Autocomplete,AMap.Transfer',
    addToolbar: 'https://cache.amap.com/lbs/static/addToolbar.js',
    css: 'https://cache.amap.com/lbs/static/main1119.css',
    svr: 'c38fedb56d61d5fcaf1547bb50fb7e2e',
    speed: 30, //单位 km/h
    city: '永州市',
    linesearch: null,
    _createScript: function (config) {
        var script = document.createElement('script');
        script.type = config.type || 'text/javascript';
        script.async = config.async;
        script.charset = config.charset || 'utf-8';
        script.src = config.url;
        //script.src = config.url + '?v=' + new Date().getTime();
        script.id = config.id || '';
        return script;
    },
    onCreateScript: function (config) {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = config.url;
        if (script.attachEvent)
            script.attachEvent("onreadystatechange", config.callback);
        else {
            script.onload = function () {
                script.onload = function () {};
                setTimeout(config.callback, 10);
            };
        }
        document.body.appendChild(script);
    },
    onLoadScript: function (config) {
        var body = document.getElementsByTagName('head')[0],
            node = this._createScript({
                id: config.id + '-js',
                url: config.url,
                async: config.async
            });

        // if (node.attachEvent)
        //     node.attachEvent("onreadystatechange", config.callback);
        // else {
        //     node.onload = function () {
        //         node.onload = function () { };
        //         setTimeout(config.callback, 7);
        //     };
        // }
        node.onload = function () {
            node.onload = function () {};
            if (config.callback) setTimeout(config.callback, 2000);
        };
        body.appendChild(node);
    },
    onLoadStyle: function (id, url, callback) {

        var isload = true;
        var link = document.createElement('link');
        var head = document.getElementsByTagName('head')[0];
        var engine = window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/) || 0;

        if (engine[2] || engine[8] || 'WebkitAppearance' in document.documentElement.style)
            isload = false;

        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.id = id + '-css';

        if (isload)
            link.onload = function () {
                link.onload = function () {};
                setTimeout(callback, 10);
            }
        else
            var loadInterval = setInterval(function () {
                for (var i = 0; i < document.styleSheets.length; i++) {
                    var sheet = document.styleSheets[i];
                    if (sheet.href == link.href) {
                        clearInterval(loadInterval);
                        return callback();
                    }
                }
            }, 10);
        link.href = url + '?v=' + new Date().getTime();
        head.appendChild(link);
    },
    onRemoveStyle: function (id) {
        var allcss = document.getElementsByTagName('link');
        for (var i = 0; i < allcss.length; i++) {
            if (allcss[i].id == id) {
                allcss[i].parentNode.removeChild(allcss[i]);
            }
        }
    },
    onInitLineSerach: function (config) {
        // debugger
        this.linesearch = new AMap.LineSearch({
            pageIndex: 1,
            city: this.city,
            pageSize: 2,
            extensions: 'all'
        });
    },
    onSedToTime: function (value) {
        if (value === Array) return '';
        var secondTime = parseInt(value); // 秒
        var minuteTime = 0; // 分
        var hourTime = 0; // 小时
        if (secondTime > 60) {
            minuteTime = parseInt(secondTime / 60);
            secondTime = parseInt(secondTime % 60);

            if (minuteTime > 60) {
                hourTime = parseInt(minuteTime / 60);
                minuteTime = parseInt(minuteTime % 60);
            }
        }
        var result = "" + parseInt(secondTime) + "秒";

        if (minuteTime > 0) {
            result = "" + parseInt(minuteTime) + "分" + result;
        }
        if (hourTime > 0) {
            result = "" + parseInt(hourTime) + "小时" + result;
        }
        return result;
    },
    onMiToGM: function (val) {
        if (!val) return '0km';
        val = parseInt(val);
        var sm = val / 1000;
        if (sm > 1) return (sm).toFixed(2) + 'km';
        return val + 'm';
    },
    onFomartTime: function (val) {
        if (val.length == 4) {
            return val.substr(0, 2) + ':' + val.substr(2, 4);
        }
        if (!isNaN(val)) {
            val = String(val);
            return val.substr(0, 2) + ':' + val.substr(2, 4);
        }

        return val;
    },

    onSortValue: function (arr, protp) {
        for (var j = 0; j < arr.length - 1; j++) {
            for (var i = 0; i < arr.length - 1 - j; i++) {
                if (parseInt(arr[i][protp]) > parseInt(arr[i + 1][protp])) {
                    var temp = parseInt(arr[i][protp]);
                    arr[i][protp] = parseInt(arr[i + 1][protp]);
                    arr[i + 1][protp] = temp;
                }
            }
        }
        return arr;
    },
    onGetType: function (type) {
        // debugger
        if (type == 0) return AMap.TransferPolicy.LEAST_TIME; //最快捷模式
        else if (type == 1) return AMap.TransferPolicy.LEAST_FEE; //最经济模式
        else if (type == 2) return AMap.TransferPolicy.LEAST_TRANSFER; //最少换乘模式
        else if (type == 3) return AMap.TransferPolicy.LEAST_WALK; //最少步行模式
        else if (type == 4) return AMap.TransferPolicy.MOST_COMFORT; //最舒适模式
        return AMap.TransferPolicy.NO_SUBWAY; //不乘地铁模式
    },
    onInitFuzzySerach: function (config) {
        var auto = new AMap.Autocomplete({
            input: config.input,
            city: this.city,
            type: '999901',
            datatype: 'busline',
            citylimit: true,
        });
        AMap.event.addListener(auto, "select", select);

        function select(e) {
            config.callback(e);
        };
    },
    queryParams: function (data, isPrefix) {
        isPrefix = isPrefix ? isPrefix : false
        var prefix = isPrefix ? '?' : ''
        var _result = [];
        for (var key in data) {
            var value = data[key]
            if (['', undefined, null].includes(value)) {
                continue
            }
            if (value.constructor === Function) {
                continue;
            }
            if (value.constructor === Array) {
                for (var _value in value) {
                    _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(value[_value]))
                }
            } else {
                _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
            }
        }
        return _result.length ? prefix + _result.join('&') : ''
    },
    onTransferPlan: function (config) {
        var that = this;
        var sname = config.sname;
        var ename = config.ename;
        var callback = config.callback;
        var type = config.type || 0;
        var trans = this.onGetType(type);

        var transOptions = {
            nightflag: true,
            city: this.city,
            policy: trans //乘车策略
        };
        var transfer = new AMap.Transfer(transOptions);
        // debugger
        transfer.search([{
                keyword: sname,
                city: this.city
            },
            {
                keyword: ename,
                city: this.city
            }
        ], function (status, result) {
            if (status === 'complete') {
                var rdata = that.onTransferResolve(result);
                callback(rdata);
            } else {
                callback({});
            }
        });
    },
    onAjax: function (url, option, callback) {

        var defaultOption = {
            method: 'GET',
            dataType: 'JSON'
        };

        if (typeof option === 'function') {
            callback = option
            option = defaultOption
        } else {
            for (var key in defaultOption) {
                if (defaultOption.hasOwnProperty(key) && option[key] === undefined) {
                    option[key] = defaultOption[key]
                }
            }
        }

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
                    var response = xhr.responseText;
                    if (option.dataType === 'JSON') {
                        try {
                            response = JSON.parse(response);
                        } catch (err) {
                            return callback(err)
                        }

                        callback(response)
                    } else {
                        callback(new Error(url + ' request failed'))
                    }
                }
            }
        };
        xhr.open(option.method || 'GET', url);
        xhr.send();
    },
    // onTransferSerivce: function (data, type, callback) {
    //     if (!data) return;

    //     var start = data.origin;
    //     var end = data.destination;
    //     var origin = start.lng + ',' + start.lat;
    //     var destination = end.lng + ',' + end.lat;
    //     var taxi_cost = data.taxi_cost;

    //     var param = {
    //         key: this.svr,
    //         origin: '111.618660,26.489162', //origin, //116.481028,39.989643
    //         destination: destination, //116.434446,39.90816
    //         city: this.city,
    //         cityd: this.city,
    //         nightflag: 1,
    //         strategy: type, //0：最快捷模式;1：最经济模式;2：最少换乘模式;3：最少步行模式;5：不乘地铁模式
    //     };
    //     var url = 'https://restapi.amap.com/v3/direction/transit/integrated?v=1&' + this.queryParams(param);
    //     this.onAjax(url, {}, function (rst) {
    //         callback(rst);
    //     });

    // },
    onTransferResolve: function (data) {
        if (!data) return {};
        var result = {
            plans: [],
            cost: (parseFloat(data.taxi_cost)).toFixed(2)
        };

        var srt = [];
        var plans = data.plans;

        var plans = this.onSortValue(plans, 'distance');
        //获取方案
        for (var i = 0; i < plans.length; i++) {
            var sgmet = [];
            var plan = plans[i];
            var segments = plan.segments;

            //获取线路
            for (var j = 0; j < segments.length; j++) {
                var item = segments[j];
                var transit = item.transit;

                if (item.transit_mode != 'BUS')
                    continue;

                if (!transit || !transit.lines || transit.lines.length <= 0)
                    continue;

                var on_station = transit.on_station || {};
                var off_station = transit.off_station || {};

                var bus = {
                    off_station: off_station.name,
                    on_station: on_station.name,
                    via_num: transit.via_num,
                    via_stops: transit.via_stops,
                    trip: this.onTransferGetCars(transit.lines)
                };
                //  console.log(plan)
                var b = [];
                for (var s = 0; s < plan.segments.length; s++) {
                    var a = plan.segments[s].instruction;
                    //              	console.log(a.indexOf("步"));
                    if (a.indexOf("步") == 0) {
                        b.push(plan.segments[s].distance);
                    } else {
                        b.push(0);
                    }
                }
                // console.log(b);
                //console.log(b[1])

                var onedistance = b[0];
                if (b[1] == undefined) {
                    var twodistance = 0;
                } else {
                    var twodistance = b[1];
                }
                if (b[2] == undefined) {
                    var theredistance = 0;
                } else {
                    var theredistance = b[2];
                }
                if (b[3] == undefined) {
                    var theredistances = 0;
                } else {
                    var theredistances = b[3];
                }
                if (b[4] == undefined) {
                    var theredistancess = 0;
                } else {
                    var theredistancess = b[4];
                }


                sgmet.push({
                    bus: bus,
                    cost: plan.cost,
                    nightLine: plan.nightLine,
                    time: this.onSedToTime(plan.time),
                    distance: this.onMiToGM(plan.transit_distance),
                    onedistance: onedistance,
                    twodistance: twodistance,
                    theredistance: theredistance,
                    theredistances: theredistances,
                    theredistancess: theredistancess,
                });
            }

            srt.push({
                sgmet: sgmet
            });
        }
        result.plans = srt;
        return result;
    },
    onTransferGetCars: function (lines) {
        // console.log(lines)
        var cars = [];
        var name = [],
            carno = [],
            stime = [],
            etime = [];
        if (!lines || lines.length <= 0) return cars;
        for (var k = 0; k < lines.length; k++) {
            var line = lines[k];
            var type = line.type;
            if (!(type instanceof Array)) {
                if (typeof type == 'string') {
                    if (type != '普通公交线路') {
                        continue;
                    }
                }
            }
            name.push(line.name);
            carno.push(line.name.split('(')[0]);
            stime.push(this.onSedToTime(line.stime));
            etime.push(this.onSedToTime(line.etime));
        }
        if (name.length == 1) {
            cars.push({
                carno: carno[0],
                stime: stime[0],
                etime: etime[0],
                desc: name[0]
            });
        }
        if (name.length == 2) {
            cars.push({
                carno: carno[0] + '/' + carno[1],
                stime: stime[0],
                etime: etime[0],
                desc: name[0]
            });
        }
        if (name.length == 3) {
            cars.push({
                carno: carno[0] + '/' + carno[1] + '/' + carno[2],
                stime: stime[0],
                etime: etime[0],
                desc: name[0]
            });
        }
        if (name.length == 4) {
            cars.push({
                carno: carno[0] + '/' + carno[1] + '/' + carno[2] + '/' + carno[3],
                stime: stime[0],
                etime: etime[0],
                desc: name[0]
            });
        }
        return cars;

    },
    onDuplicateDecision: function (store, value) {
        if (!store || store.length <= 0) return true;
        for (var i = 0; i < store.length; i++) {
            var sgmet = store[i].sgmet;
            for (var j = 0; j < sgmet.length; j++) {
                var cars = sgmet[j].cars;
                var name = '';
                for (var k = 0; k < cars.length; k++) {
                    name += cars[k].carno;
                }
                if (name == value) return false
            }
        }
        return true;
    },
    onTransferResolveExt: function (data) {

        if (!data)
            return {};

        var route = data.route;

        var result = {
            plans: [],
            distance: this.onMiToGM(route.distance),
            cost: (parseFloat(route.taxi_cost)).toFixed(2)
        };

        var plans = this.onSortValue(route.transits, 'duration');
        var nameKy = [];
        for (var i = 0; i < plans.length; i++) {
            var scheme = [];
            var vpl = plans[i];
            var segments = vpl.segments;

            for (var j = 0; j < segments.length; j++) {
                var routes = [];
                var bus = segments[j].bus;
                var buslines = bus.buslines || [];
                var carKyName = '';
                for (var k = 0; k < buslines.length; k++) {
                    var line = buslines[k];
                    var type = line.type;

                    if (type != '普通公交线路')
                        continue;

                    var carno = line.name.split('(')[0];
                    var stime = this.onSedToTime(line.start_time);
                    var etime = this.onSedToTime(line.end_time);
                    var distance = this.onMiToGM(line.distance);
                    var time = this.onSedToTime(line.duration);
                    carKyName += carno;
                    routes.push({
                        time: time,
                        carno: carno,
                        stime: stime,
                        etime: etime,
                        distance: distance,
                        via_num: line.via_num,
                        via_stops: line.via_stops,
                        arrival_stop: line.arrival_stop.name, //此段下车站
                        departure_stop: line.departure_stop.name //此段起乘站信息
                    });
                }
                if (nnameKy[carKyName]) {
                    continue;
                } else {
                    nameKy[carKyName] = carKyName;
                }
                scheme.push({
                    routes: routes
                });
            }
            var item = {
                cost: vpl.cost, //单位：元
                nightflag: vpl.nightflag, //0：非夜班车；1：夜班车,
                walking_distance: vpl.walking_distance, //此方案总步行距离
                distance: this.onMiToGM(vpl.distance),
                time: this.onSedToTime(vpl.duration),
                segments: scheme
            };

            result.plans.push(item);
        }
        return result;
    },
    //根据线路名称获取线路详情name 线路名称:例如776,callback：回调函数
    onGetRouteInfo: function (name, callback) {
        this.linesearch.search(name, function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                callback(result);
            } else {
                callback([]);
            }
        });
    },
    onGetKeyWord: function (keyWord, callback) {
        var param = {
            key: this.svr,
            keywords: keyWord,
            type: '',
            location: '',
            city: this.city,
            citylimit: true,
            datatype: 'bus',
            output: 'json'
        };

        var url = 'https://restapi.amap.com/v3/assistant/inputtips?v=1&' + this.queryParams(param);
        this.onAjax(url, {}, function (data) {
            if (!data) callback([]);
            var rst = data.tips || [];
            callback(rst);
        });
    },
    onImport: function (callback) {
        var that = this;
        this.onLoadStyle('map-css', this.css, function () {
            that.onLoadScript({
                id: 'gd-map',
                url: that.api,
                async: true,
                callback: function () {
                    callback(that);
                }
            });
        });
    }
};